#include "image.h"
#include "QFileDialog"
#include "QMouseEvent"
#include "QPixmap"
#include "cadre.h"

Image::Image(const QString &fichier) :
    ImageClickable(NULL),_facteurZoom(1),
    _source(NULL),_destination(NULL),_cadre(NULL),selection(false)
{
    connect(this,SIGNAL(doubleClicked(QMouseEvent*)),this,SLOT(onMouseDoubleClicked(QMouseEvent*)));
    connect(this,SIGNAL(clicked(QMouseEvent*)),this,SLOT(onMouseClicked(QMouseEvent*)));
    connect(this,SIGNAL(mouseMoved(QMouseEvent*)),this,SLOT(onMouseMove(QMouseEvent*)));
    loadImage(fichier);
}

void Image::zoom(double x)
{
    if(_source!=NULL && x>0)
    {
      _facteurZoom*=x;
       QSize taille = pixmap()->size()*_facteurZoom;
       resize(taille);
    }
}

Image::~Image()
{
    if(_source!=NULL)
    {
        delete _source;
        _source = NULL;
    }
    if(_destination!=NULL)
    {
        delete _destination;
        _destination = NULL;
    }
}

void Image::loadImage(const QString &fichier)
{
    if(!fichier.isEmpty())
    {
        if(_source!=NULL)
            delete _source;
        if(_destination!=NULL)
            delete _destination;
        _source = new QPixmap();
        _destination = new QPixmap();
        _source->load(fichier);
        (*_destination) = QPixmap::fromImage(_source->toImage());
        this->setPixmap(*_source);
        adjustSize();
    }
}

void Image::setCadre(Cadre *cadre)
{
   _cadre = cadre;
   connect(cadre,SIGNAL(deSelection()),this,SLOT(onDeselection()));
}

void Image::recadrage()
{
    QRect rect(_posRect,size());
    this->setPixmap(_destination->copy(rect));
    this->adjustSize();
}

void Image::onMouseClicked(QMouseEvent *event)
{
    _mousePos = event->globalPos();
    if(event->buttons()==Qt::LeftButton)
    {
        if(_cadre!=NULL)
            _cadre->majSelection();
        selection = true;
    }
}

void Image::onMouseMove(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        if(_source!=NULL)
        {
            _posRect = QPoint(_posRect.x()+(event->globalX()-_mousePos.x()),_posRect.y()+(event->globalY()-_mousePos.y()));
            if(_posRect.x()<0)
                _posRect.setX(0);
            if(_posRect.y()<0)
                _posRect.setY(0);
            recadrage();
            _mousePos = event->globalPos();
        }
    }
}

void Image::onMouseDoubleClicked(QMouseEvent *event)
{
    QString fichier = QFileDialog::getOpenFileName(this, "Ouvrir un fichier", QString(), "Images (*.png *.gif *.jpg *.jpeg)");
    loadImage(fichier);
}
